package com.lm.survey.web;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.lm.survey.lifecycle.GeneralLifecycle;
import com.lm.survey.logic.ActivityParticipantLogic;
import com.lm.survey.logic.Cache;
import com.lm.survey.logic.MP3DataBase;
import com.lm.survey.logic.QuestionItemLogic;
import com.lm.survey.logic.QuestionnaireGroupLogic;
import com.lm.survey.logic.QuestionnaireLogic;
import com.lm.survey.logic.SecurityLogic;
import com.lm.survey.model.Activity;
import com.lm.survey.model.MP3File;
import com.lm.survey.model.Participant;
import com.lm.survey.model.QuestionGroup;
import com.lm.survey.model.QuestionItem;
import com.lm.survey.model.QuestionPackage;
import com.lm.survey.model.Questionnaire;
import com.lm.survey.model.User;
import com.lm.survey.util.Config;
import com.lm.survey.util.JsonHelper;
import com.lm.survey.util.RequestToPojo;

public class AttachmentManagerServlet extends BaseServlet {

    public void getFile(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        int itemId = Integer.parseInt(request.getParameter("itemId"));
        QuestionItemLogic logic = new QuestionItemLogic();
        QuestionItem item = logic.getQuestionItem(itemId);
        String template = item.getAnswer();
        Activity activity = (Activity) request.getSession().getAttribute(
                "activity");
        Questionnaire question = (Questionnaire) request.getSession()
                .getAttribute("question");

        Participant p = (Participant) request.getSession().getAttribute(
                "participant");

        String tempFile = makeTempFile(template, activity.getProjectId(),activity.getId(), p
                .getId(), itemId);
        ;
        String uerFile = request.getContextPath() + tempFile;
        response.getWriter().print(uerFile);
        response.getWriter().close();

    }

    
    
    public void getTemplateFile(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String pkgId = request.getParameter("pkgId");
        QuestionPackage pkg = Cache.instance().getPkg(pkgId);
        String templateFile = null;
        if(pkg.isOnlySelfTest()){
            templateFile = "user_self.template.xml";
        }else{
            templateFile = "user_with_rela.template.xml";
        }
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        response.setHeader("Content-Disposition", "inline;filename="+templateFile);
        File source = new File(Config.instance().getStringProperty("TemplatePath")+File.separator+templateFile);
        this.copy(source,response.getOutputStream());
        
        

    
    }
    
    

    String makeTempFile(String template, int projectId, int activityId,int participantId,
            int itemId) {
        try {
            String projectPath = Config.instance().getStringProperty(
                    "ItemAttachmentPath")
                    + File.separator
                    + projectId
                    + File.separator
                    + activityId
                    + File.separator
                    + participantId;
            File filePorject = new File(projectPath);
            if (!filePorject.exists()) {
                filePorject.mkdirs();
            }
            String targetFile = projectPath + File.separator + itemId + "_"
                    + template;
            if (new File(targetFile).exists()) {

            } else {
                File templateFile = new File(Config.instance()
                        .getStringProperty("TemplatePath")
                        + File.separator + template);
                copy(templateFile, new File(targetFile));

            }
            return Config.instance().getStringProperty(
                    "ItemAttachmentContextPath")
                    + "/"
                    + projectId
                    + "/"
                    +activityId
                    + "/"
                    + participantId                   
                    + "/"
                    + itemId
                    + "_" + template;

        } catch (Exception ex) {
            throw new RuntimeException(ex.getMessage());
        }

    }
    
    boolean copy(File fileFrom, OutputStream out) {
        try {
            FileInputStream in = new java.io.FileInputStream(fileFrom);
            byte[] bt = new byte[1024];
            int count;
            while ((count = in.read(bt)) > 0) {
                out.write(bt, 0, count);
            }
            in.close();
            out.close();
            return true;
        } catch (IOException ex) {
            return false;
        }
    }

    boolean copy(File fileFrom, File fileTo) {
        try {
            FileInputStream in = new java.io.FileInputStream(fileFrom);
            FileOutputStream out = new FileOutputStream(fileTo);
            return this.copy(fileFrom, out);
        } catch (IOException ex) {
            return false;
        }
    }

    public static void main(String[] args) {
        AttachmentManagerServlet main = new AttachmentManagerServlet();
        String template = "template_eqtask3.doc";
        int projectId = 1;
        int participantId = 2;
        int itemId = 12;
        String str = main.makeTempFile(template, projectId,12323, participantId,
                itemId);
        System.out.println(str);

    }

}
